package sunsun.xiaoli.jiarebang.app;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.*;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.itboye.pondteam.app.MyApplication;
import com.itboye.pondteam.utils.Const;
import com.itboye.pondteam.utils.CrashHandler;
import com.itboye.pondteam.utils.loadingutil.MAlert;
import com.orhanobut.logger.Logger;
import sunsun.xiaoli.jiarebang.R;
import sunsun.xiaoli.jiarebang.beans.AppConfig;
import sunsun.xiaoli.jiarebang.beans.SearchDeviceInfo;
import sunsun.xiaoli.jiarebang.device.*;
import sunsun.xiaoli.jiarebang.device.pondteam.*;
import sunsun.xiaoli.jiarebang.utils.AqDeviceFind;
import sunsun.xiaoli.jiarebang.utils.wifiutil.AqSmartConfig;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import static sunsun.xiaoli.jiarebang.utils.Util.isFeatures;

//import org.android.agoo.huawei.HuaWeiRegister;

/**
 * Created by admin on 2016/12/6.
 */

public class App extends MyApplication {
    //    private LanguageSettingUtil languageSetting;
//    private SwitchLanguageObservable switchLangObs;
//    public List<WeakReference<Activity>> activityList = new LinkedList<>();
    public static App instance;
    public AddDeviceActivity mAddDeviceUi;
    public ArrayList<SearchDeviceInfo> mMyDeviceList = null;
    public DeviceActivity mDeviceUi;
    public VersionUpdateActivity versionUpdateActivityUI = null;
    public ActivityStepThree addDeviceThird = null;
    //    public Database mDatabase;
    public VersionUpdateActivity updateActivityUI;
    public ManualAddDeviceActivity mManualAddDeviceUi;
    public ActivityStepFirst addDeviceFirst;
    public ActivityInputWifiAndPass addDeviceInputWifi;
    private AqDeviceFind aqDeviceFind;
    public AddPondDevice addPondDeviceUI;//添加设备第一个界面
    public ActivityPondDeviceDetail pondDeviceDetailUI;//设备详情UI
    public ActivityZiDong ziDongUI;
    public ActivityUvLamp uvLampUI;
    public ActivityShouDong shoudongUI;
    public ActivityChaZuoBDetail chazuoBDetail;
    public EditDeviceActivity mEditDeviceUi;
    public BindCameraDeviceActivity mBindCameraDeviceUi;

    public List<WeakReference<Activity>> getActivityList() {
        return activityList;
    }

    public AqSmartConfig aqSmartConfig;
    private static RequestQueue queue;

    public void setActivityList(List<WeakReference<Activity>> activityList) {
        this.activityList = activityList;
    }

    public static App getInstance() {
        return instance;
    }

//    public PushAgent mPushAgent;
//
//
//    Tencent mTencent = null;
//
//    public Tencent getmTencent() {
//        return mTencent;
//    }
//
//    public void setmTencent(Tencent mTencent) {
//        this.mTencent = mTencent;
//    }
//
//    public IWXAPI iwxapi;
//
//    public IWXAPI getIwxapi() {
//        return iwxapi;
//    }
//
//    public void setIwxapi(IWXAPI iwxapi) {
//        this.iwxapi = iwxapi;
//    }

    Gson gson;

    public String token;
    public boolean isStartSearch = true;
    public String name[] = null;
    public SQLiteDatabase db;// 数据库
    private final String DB_FILENAME = "itboye.db";
    private String DB_PATH;


    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        initLanguage();
//        MobclickAgent.setCatchUncaughtExceptions(true);
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(this);
        Logger.init("request_params");
        gson = new Gson();//在这里为应用设置异常处理程序，然后我们的程序才能捕获未处理的异常
        aqSmartConfig = new AqSmartConfig(this);
        mLanDeviceList = new ArrayList<>();
        queue = Volley.newRequestQueue(this);
//        mDatabase = new Database(this);
//        mMyDeviceList = mDatabase.getAllDeviceInfo();
        mMyDeviceList = new ArrayList<>();
        if (!isFeatures()) {//不是虚拟机的情况
//            SDKInitializer.initialize(getApplicationContext());
            aqDeviceFind = new AqDeviceFind(mHandler);
            aqDeviceFind.start(AppConfig.Find_Device_Port);
        }
//        Logger.init("down");
        init(getApplicationContext());
        initBroadcast();
    }

    private void initGreenDao() {

        // 初始化LitePal数据库
//        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "xiaoli.db");
//        SQLiteDatabase db = helper.getWritableDatabase();
//        DaoMaster daoMaster = new DaoMaster(db);
//        daoSession = daoMaster.newSession();
    }


    private void restartApplication() {


        System.exit(0);


//        ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(ACTIVITY_SERVICE);
//        am.restartPackage(getPackageName());
//
//        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);
    }

    private void initBroadcast() {
//        IntentFilter intentFilter = new IntentFilter(Const.RE_LOGIN);
//        registerReceiver(borad, intentFilter);
    }

//    BroadcastReceiver borad = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            Activity activityTop = null;
//            for (WeakReference<Activity> activity : MyApplication.getInstance().activityList) {
//                if (activity.get() != null) {
//                    if (isForeground(getApplicationContext(), activity.get().getClass().getName())) {
//                        activityTop = activity.get();
//                    }
//                }
//
//            }
//            MAlert.alert(getString(R.string.re_login));
//            try {
//                Intent intent1 = new Intent();
//                intent1.setClass(context, LoginActivity.class);
//                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                activityTop.startActivity(intent1);
//            } catch (Exception e) {
//
//            }
//        }
//    };


    private void init(Context context) {

        try {
            DB_PATH = context.getCacheDir().getCanonicalPath() + "/address";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        db = openDataBase();
//        db.close();
    }

    private SQLiteDatabase openDataBase() {
        try {
            String dbFileName = DB_PATH + "/" + DB_FILENAME;
            File dir = new File(DB_PATH);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            if (!new File(DB_PATH, DB_FILENAME).exists()) {
                new File(DB_PATH, DB_FILENAME).createNewFile();
                InputStream is = getResources().openRawResource(R.raw.itboye);
                FileOutputStream fos = new FileOutputStream(dbFileName);
                byte[] buffer = new byte[8192];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
            }
            db = SQLiteDatabase.openOrCreateDatabase(dbFileName, null);
            return db;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        @SuppressLint("WrongConstant") ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;
    }

    public void addActivity(Activity activity) {
        activityList.add(new WeakReference<Activity>(activity));
    }

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            SearchDeviceInfo msgObj = (SearchDeviceInfo) msg.obj;
            // 查找到一个设备
            findNewDeviceProcess(msgObj);
            return;

        }
    };

    public ArrayList<SearchDeviceInfo> mLanDeviceList = null;
    ArrayList<String> arrayListDid = new ArrayList<>();

    private void findNewDeviceProcess(SearchDeviceInfo deviceInfo) {
        // 排除无效信息
        if (deviceInfo == null) {
            return;
        }
        if (deviceInfo.getDid() == null) {
            return;
        }
        if (deviceInfo.getPwd() == null) {
            return;
        }
        //排除设备类型为空
        if (deviceInfo.getType() == null) {
            return;
        }
        //排除设备类型为空
        if (deviceInfo.getType().equals("")) {
            return;
        }
        // 局域网设备列表刷新
        for (int i = 0; i < mLanDeviceList.size(); i++) {
            SearchDeviceInfo d = mLanDeviceList.get(i);
            if (d.getDid().equals(deviceInfo.getDid())) {
                if (!d.getPwd().equals(deviceInfo.getPwd())) {
                    //设备密码有变更
                    d.setPwd(deviceInfo.getPwd());
                    arrayListDid.remove(d.getDid());
                    mLanDeviceList.remove(i);
                    break;
                }
            }
        }
        int position = arrayListDid.indexOf(deviceInfo.getDid());
        if (addDeviceThird != null) {
            addDeviceThird.findNewDeviceInfo(deviceInfo);
        }
        if (position == -1) {
            // 添加新设备信息到局域网设备信息列表
            arrayListDid.add(deviceInfo.getDid());
            mLanDeviceList.add(deviceInfo);
        }
        if (mAddDeviceUi != null && position == -1) {
            mAddDeviceUi.refreshDeviceList();
        }
    }


    // 遍历所有Activity并finish
    public void exit() {
        for (WeakReference<Activity> activity : activityList) {
            if (activity.get() != null) {
                activity.get().finish();
            }

        }
        System.exit(0);
    }


    /**
     * @return the queue
     */
    public static RequestQueue getQueue() {
        return queue;
    }

    //
    public static <T> void addRequest(Request<T> request) {
        request.addMarker("itboye");
        getQueue().add(request);
    }

}
